/**
 * 
 */
package leetCode;

/**
 * @author zhong
 *
 */
public class BuddyStrings {
	public boolean buddyStrings(String A, String B) {
		if (A.length() != B.length()) {
			return false;
		}
		int n = A.length();
		int freqA[] = new int[26];
		int freqB[] = new int[26];
		int diffCnt = 0;
		char a = 0, b = 0;
		for (int i = 0; i < n; i++) {
			freqA[A.charAt(i) - 'a']++;
			freqB[B.charAt(i) - 'a']++;
			if (A.charAt(i) != B.charAt(i)) {
				if (diffCnt == 0) {// 出现第一次不同，
					a = A.charAt(i);
					b = B.charAt(i);
				} else if (diffCnt == 1) {// 出现第二次不同，要求字符和上次交换
					if (A.charAt(i) != b || B.charAt(i) != a) {
						return false;
					}
				} else {// 出现多词不同
					return false;
				}
				diffCnt += 1;
			}
		}
		if (diffCnt == 0) {// 验证是否有相同的字符
			for (int i = 0; i < 26; i++) {
				if (freqA[i] > 1) {
					return true;
				}
			}
		}
		return diffCnt == 2;
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		String A = "dd", B = "dd";
		System.out.println(new BuddyStrings().buddyStrings(A, B));

	}

}
